package com.cqjtu.tto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqjtu.tto.dao.mapper.*;
import com.cqjtu.tto.dao.pojo.EmployeePerformance;
import com.cqjtu.tto.dao.pojo.Role;
import com.cqjtu.tto.dao.pojo.SysUser;
import com.cqjtu.tto.dao.pojo.SysUserRole;
import com.cqjtu.tto.service.EmployeePerformanceService;
import com.cqjtu.tto.service.RoleService;
import com.cqjtu.tto.service.SysUserService;
import com.cqjtu.tto.vo.EmployeePerformanceVo;
import com.cqjtu.tto.vo.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工绩效 服务实现类
 * </p>
 *
 * @author MrLuo
 * @since 2021-12-14
 */
@Service
public class EmployeePerformanceServiceImpl extends ServiceImpl<EmployeePerformanceMapper, EmployeePerformance> implements EmployeePerformanceService {
    @Autowired
    private EmployeePerformanceMapper employeePerformanceMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 定时生成员工的每月绩效
     * 1.先获取公司的全部员工
     * 2.获取公司的角色（包含了角色的考核标准）
     * 3.获取每个员工从上个月15日到当前完成的任务数量
     * 4.生成每个员工的绩效考核
     * 5.插入每个员工的绩效考核
     */
    @Scheduled(cron = "0 0 0 15 * ?")   // 每月的15日0时0分0秒触发 cron = "0 0 0 15 * ?"
    @Override
    public void creatEmployeePerformance() {
        // 获取公司角色
        List<Role> roles = roleMapper.selectList(new LambdaQueryWrapper<Role>().eq(Role::getRoleDeleted, 0));
        Map<String, Integer> map = new HashMap<>();
        roles.forEach(role -> {
            map.put(role.getRoleName(), role.getRoleAssessmentIndex());
        });
        // 获取公司全部员工
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().isNotNull(SysUser::getDepartmentId));
        // 当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 上次结算时间
        LocalDateTime priorDateTime = currentDateTime.plusMonths(-1);
        List<EmployeePerformance> employeePerformances = new ArrayList<>();
        // 获取每个员工的任务完成数生成每个员工的绩效考核
        sysUsers.forEach(sysUser -> {
            Integer taskCount = taskMapper
                    .getEmployeeCompleteTaskCount(priorDateTime,
                            currentDateTime,
                            sysUser.getUserId());
            // 生成当前员工的绩效考核
            EmployeePerformance employeePerformance = new EmployeePerformance();
            employeePerformance.setUserId(sysUser.getUserId());
            employeePerformance.setEmployeePerformanceCreat(currentDateTime);
            // 获取该员工的角色以判断是否达标
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(
                    new LambdaQueryWrapper<SysUserRole>()
                            .eq(SysUserRole::getUserId, sysUser.getUserId()));
            List<Long> ids = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

            // 通过ids查询角色
            List<Role> roles1 = roleMapper.listRoleByRoleId(ids); // 当前用户的角色
            Set<String> collect = roles1.stream().map(Role::getRoleName).collect(Collectors.toSet());
            // 判断是否是主管之类的
            if (collect.contains("admin")){
                // 管理员
                if (taskCount >= map.get("admin")){
                    // 达标
                    employeePerformance.setStandard(1);
                }
                else
                    employeePerformance.setStandard(0);
            }
            else if (collect.contains(map.get("leader"))){
                // 领导
                if (taskCount >= map.get("leader")){
                    // 达标
                    employeePerformance.setStandard(1);
                }
                else
                    employeePerformance.setStandard(0);
            }
            else if (collect.contains(map.get("skilled-worker"))){
                // 主管
                if (taskCount >= map.get("skilled-worker")){
                    // 达标
                    employeePerformance.setStandard(1);
                }
                else
                    employeePerformance.setStandard(0);
            }
            else{
                if (taskCount>=10){
                    // 达标
                    employeePerformance.setStandard(1);
                }
                else
                    employeePerformance.setStandard(0);
            }
            employeePerformances.add(employeePerformance);
        });
        // 插入员工的绩效
        this.saveBatch(employeePerformances);
    }

    /**
     * 获取员工上次的绩效信息
     * @return
     */
    @Override
    public Results listEmployeePerformanceLastMonth() {
        LocalDate now = LocalDate.now();
        // 获取上次发工资时间
        LocalDate pDate = now.plusMonths(-1 * (now.getDayOfMonth() < 15 ? 1 : 0));
        LocalDate lastDate = LocalDate.of(pDate.getYear(), pDate.getMonth(), 15);
        List<EmployeePerformance> employeePerformances = employeePerformanceMapper.listEmployeePerformanceLastMonth(lastDate);
        List<SysUser> sysUsers = sysUserMapper.selectList(null);
        // 把员工id和员工名映射
        Map<Long, String> map = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        List<EmployeePerformanceVo> employeePerformanceVos = new ArrayList<>();
        employeePerformances.forEach(employeePerformance -> {
            employeePerformanceVos.add(new EmployeePerformanceVo(employeePerformance, map.get(employeePerformance.getUserId())));
        });
        return Results.success(employeePerformanceVos);
    }

    /**
     * 根据员工id获取员工的历史绩效信息
     * @param sysUserId
     * @return
     */
    @Override
    public Results listEmployeePerformanceHistoryByUserId(Long sysUserId) {
        List<EmployeePerformance> employeePerformances = this.list(new LambdaQueryWrapper<EmployeePerformance>().eq(EmployeePerformance::getUserId, sysUserId));
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, sysUserId));
        List<EmployeePerformanceVo> employeePerformanceVos = new ArrayList<>();
        employeePerformances.forEach(employeePerformance -> {
            employeePerformanceVos.add(new EmployeePerformanceVo(employeePerformance, sysUser.getUserName()));
        });
        return Results.success(employeePerformanceVos);
    }
}
